import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import styles from "./login.module.css";
import SHA512 from 'crypto-js/sha512';
import axios from 'axios';
import { Toast } from 'antd-mobile';

export default function Login() {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [showPassword, setShowPassword] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [emailError, setEmailError] = useState("");
    const [passwordError, setPasswordError] = useState("");
    const navigate = useNavigate();

    const handleLogin = async (e) => {
        e.preventDefault();
        
        // 清除之前的错误信息
        setEmailError("");
        setPasswordError("");
        
        // 验证邮箱格式
        if (!email || !/^\S+@\S+\.\S+$/.test(email)) {
            setEmailError("请输入有效的邮箱地址");
            return;
        }

        // 验证密码
        if (!password || password.length < 6) {
            setPasswordError("密码长度至少为6位");
            return;
        }

        setIsSubmitting(true);

        try {
            // 对密码进行SHA512哈希，与注册时保持一致
            const hashedPassword = SHA512(password).toString();
            
            const response = await axios.post("http://localhost:3000/login", {
                email,
                password: hashedPassword // 发送SHA512哈希后的密码
            });

            if (response.data.code === 200) {
                Toast.show({
                    icon: 'success',
                    content: '登录成功！',
                });
                // 可以在这里存储用户信息到localStorage或状态管理
                localStorage.setItem('userId', response.data.userId);
                localStorage.setItem('userEmail', email);
                
                // 登录成功后跳转到主页或其他页面
                setTimeout(() => {
                    navigate('/home'); // 根据你的路由配置调整
                }, 1000);
            } else if (response.data.code === 400) {
                Toast.show({
                    icon: 'fail',
                    content: response.data.message,
                });
            } else {
                Toast.show({
                    icon: 'fail',
                    content: '登录失败，请稍后重试',
                });
            }
        } catch (error) {
            console.error('登录错误:', error);
            if (error.response && error.response.data) {
                Toast.show({
                    icon: 'fail',
                    content: error.response.data.message || '登录失败',
                });
            } else if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
                Toast.show({
                    icon: 'fail',
                    content: '请求超时，请检查网络连接',
                });
            } else if (!error.response) {
                Toast.show({
                    icon: 'fail',
                    content: '网络错误，请检查网络连接',
                });
            } else {
                Toast.show({
                    icon: 'fail',
                    content: '登录失败，请稍后重试',
                });
            }
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <div className={styles.container}>
            {/* Curved header with logo */}
            <div className={styles.header}>
                <div className={styles.logo}>
                    <div className={styles.logoDot}></div>
                    <div className={styles.logoDot}></div>
                    <div className={styles.logoDot}></div>
                    <div className={styles.logoDot}></div>
                </div>
            </div>

            {/* Login content */}
            <div className={styles.content}>
                <h1 className={styles.title}>登录ai心理健</h1>

                <form onSubmit={handleLogin}>
                    {/* Email field */}
                    <div className={`${styles.formGroup} ${emailError ? styles.hasError : ''}`}>
                        <label>电子邮件地址</label>
                        <div className={styles.inputContainer}>
                            <span className={styles.inputIcon}>
                                <svg viewBox="0 0 24 24" width="20" height="20">
                                    <path fill="#888888" d="M20,4H4C2.897,4,2,4.897,2,6v12c0,1.103,0.897,2,2,2h16c1.103,0,2-0.897,2-2V6C22,4.897,21.103,4,20,4z M20,6v0.511
                                    l-8,6.223l-8-6.222V6H20z M4,18V9.044l7.386,5.745C11.566,14.93,11.783,15,12,15s0.434-0.07,0.614-0.211L20,9.044L20.002,18H4z"></path>
                                </svg>
                            </span>
                            <input
                                type="email"
                                placeholder="Koto1234@gmail.com"
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                                required
                            />
                        </div>
                        {emailError && (
                            <div className={styles.errorMessage}>
                                <span className={styles.errorIcon}>⚠️</span>
                                {emailError}
                            </div>
                        )}
                    </div>

                    {/* Password field */}
                    <div className={`${styles.formGroup} ${passwordError ? styles.hasError : ''}`}>
                        <label>密码</label>
                        <div className={styles.inputContainer}>
                            <span className={styles.inputIcon}>
                                <svg viewBox="0 0 24 24" width="20" height="20">
                                    <path fill="#888888" d="M17,9V7c0-2.8-2.2-5-5-5S7,4.2,7,7v2c-1.7,0-3,1.3-3,3v7c0,1.7,1.3,3,3,3h10c1.7,0,3-1.3,3-3v-7
                                    C20,10.3,18.7,9,17,9z M9,7c0-1.7,1.3-3,3-3s3,1.3,3,3v2H9V7z M18,19c0-0.6-0.4,1-1,1H7c-0.6,0-1-0.4-1-1v-7c0-0.6,0.4-1,1-1
                                    h10c0.6,0,1,0.4,1,1V19z"></path>
                                </svg>
                            </span>
                            <input
                                type={showPassword ? "text" : "password"}
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                placeholder="******************"
                                required
                            />
                            <button
                                type="button"
                                className={styles.togglePassword}
                                onClick={() => setShowPassword(!showPassword)}
                            >
                                {showPassword ? (
                                    <svg viewBox="0 0 24 24" width="20" height="20">
                                        <path fill="#CCCCCC" d="M12,4C4.676,4,2,12,2,12s2.676,8,10,8s10-8,10-8S19.324,4,12,4z M12,16c-2.206,0-4-1.794-4-4s1.794-4,4-4s4,1.794,4,4S14.206,16,12,16z M12,10c-1.103,0-2,0.897-2,2s0.897,2,2,2s2-0.897,2-2S13.103,10,12,10z"></path>
                                    </svg>
                                ) : (
                                    <svg viewBox="0 0 24 24" width="20" height="20">
                                        <path fill="#CCCCCC" d="M12,4C4.676,4,2,12,2,12s2.676,8,10,8s10-8,10-8S19.324,4,12,4z M12,16c-2.206,0-4-1.794-4-4s1.794-4,4-4s4,1.794,4,4S14.206,16,12,16z M12,10c-1.103,0-2,0.897-2,2s0.897,2,2,2s2-0.897,2-2S13.103,10,12,10z M21.707,2.293c-0.391-0.391-1.023-0.391-1.414,0L2.293,20.293c-0.391,0.391-0.391,1.023,0,1.414C2.488,21.902,2.744,22,3,22s0.512-0.098,0.707-0.293L21.707,3.707C22.098,3.316,22.098,2.684,21.707,2.293z"></path>
                                    </svg>
                                )}
                            </button>
                        </div>
                        {passwordError && (
                            <div className={styles.errorMessage}>
                                <span className={styles.errorIcon}>⚠️</span>
                                {passwordError}
                            </div>
                        )}
                    </div>

                    {/* Login button */}
                    <button 
                        type="submit" 
                        className={`${styles.loginButton} ${isSubmitting ? styles.submitting : ''}`}
                        disabled={isSubmitting}
                    >
                        {isSubmitting ? '登录中...' : '登录'} <span className={styles.arrow}>→</span>
                    </button>
                </form>

                {/* Social login options */}
                <div className={styles.socialLogin}>
                    <button className={styles.socialBtn}>
                        <svg viewBox="0 0 24 24" width="24" height="24">
                            <path fill="#07C160" d="M8.691,2.188C3.891,2.188,0,5.476,0,9.53c0,2.212,1.17,4.203,3.002,5.55c0.099,0.075,0.205,0.162,0.285,0.275
                            c0.545,0.764-0.161,2.659-0.161,2.659s1.589-0.834,2.305-1.025c0.425-0.107,0.762-0.026,0.977,0.006
                            C7.107,17.247,7.891,17.53,8.691,17.53c4.8,0,8.691-3.288,8.691-7.342c0-4.053-3.891-7.342-8.691-7.342"></path>
                            <path fill="#07C160" d="M18.533,22.188c3.562,0,6.467-2.438,6.467-5.448c0-3.009-2.905-5.447-6.467-5.447c-3.563,0-6.467,2.438-6.467,5.447
                            c0,1.64,0.867,3.117,2.228,4.118c0.073,0.055,0.151,0.12,0.211,0.204c0.404,0.568-0.119,1.974-0.119,1.974s1.18-0.619,1.711-0.76
                            c0.316-0.08,0.566-0.02,0.725,0.004c0.335,0.026,0.683,0.071,1.039,0.071"></path>
                        </svg>
                    </button>
                    <button className={styles.socialBtn}>
                        <svg viewBox="0 0 24 24" width="24" height="24">
                            <path fill="#000" d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2
                            .81-3.27.82-1.31.02-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02
                            2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65
                            4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04
                            3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11"></path>
                        </svg>
                    </button>
                    <button className={styles.socialBtn}>
                        <svg viewBox="0 0 24 24" width="24" height="24">
                            <rect fill="#1677ff" width="24" height="24" rx="6" />
                            <path fill="white" d="M17,8H7c-0.6,0-1,0.4-1,1v1c0,0.6,0.4,1,1,1h10c0.6,0,1-0.4,1-1V9C18,8.4,17.6,8,17,8z" />
                            <path fill="white" d="M17,13H7c-0.6,0-1,0.4-1,1v1c0,0.6,0.4,1,1,1h10c0.6,0,1-0.4,1-1v-1C18,13.4,17.6,13,17,13z" />
                        </svg>
                    </button>
                </div>

                {/* Register and forgot password links */}
                <div className={styles.footer}>
                    <p>
                        没有账户? <a href="/register" className={styles.registerLink}>注册。</a>
                    </p>
                    <p>
                        <a href="/forgot-password" className={styles.forgotLink}>忘记密码</a>
                    </p>
                </div>
            </div>
        </div>
    );
}
